using System;
using System.Timers;
using System.Linq;
using System.Collections.Generic;

namespace QntPlatform.BinanceApi
{
    public class TickerListener
    {

        public static string GetExchangeSign(IExchange exchange)
        {
            return exchange.Name + "_" + exchange.Currency;
        }
        public string GetExchangeSign()
        {
            return GetExchangeSign(Exchange);
        }
        IExchange Exchange;

        static List<TickerListener> TickerListenerList = new List<TickerListener>();
        public EventHandler<Ticker> tickerChangeEvent { get; private set; }
        public static TickerListener GetOrCreateListener(IExchange exchange)
        {
            var tickerListener = TickerListenerList.FirstOrDefault(p => GetExchangeSign(p.Exchange) == GetExchangeSign(exchange));
            if (tickerListener == null)
            {
                //JFApiClient.IsVProxySet=true;
                tickerListener = new TickerListener() { Exchange = exchange };
                TickerListenerList.Add(tickerListener);
                var names=TickerListenerList.Select(p => GetExchangeSign(p.Exchange)).ToArray();

                Log.Default().Info($"新增交易数据查询任务：{GetExchangeSign(exchange)}，现有总数量：{TickerListenerList.Count}:{string.Join('~',names)}");
                tickerListener.InitTickerChange();
            }
            return tickerListener;
        }
        public event EventHandler<Ticker> TickerChangeEvent
        {
            add
            {
                if (!timer.Enabled)
                {
                    timer.Start();
                }
                tickerChangeEvent += value;
            }
            remove
            {
                tickerChangeEvent -= value;
                if (tickerChangeEvent == null || tickerChangeEvent.GetInvocationList().Length < 1)
                {
                    timer.Stop();
                }

            }
        }

        // JFApiClient jFApi=new JFApiClient("","");
        Ticker oldTck;
        int nowNum=0;
        object lockObj=new object();
        public void InitTickerChange()
        {
            timer = new Timer(2000);
            timer.Elapsed += (p1, p2) =>
            {
                if (nowNum > 0)
                {
                    Log.Default().Info($"{GetExchangeSign(Exchange)}的timer.Elapsed竞争："+nowNum);
                    return;
                }
                lock (lockObj)
                {
                    nowNum++;
                    try
                    {
                        var re = Exchange.GetTickerAsync();
                        var tck = re.Result;
                        //    var tck = new Ticker();
                        //    var re= jFApi.getSymbolPriceTicker(Exchange.Currency).FirstOrDefault();
                        //    if(re==null) return;
                        //    tck.Buy=re.Price;
                        //     tck.Sell=re.Price;
                        //     tck.Last=re.Price;
                        if (tck == null)
                        {
                            Log.Default().Error("定时获取数据失败,返回tkc为null:" + GetExchangeSign());
                            return;
                        }
                        if (oldTck?.Buy == tck.Buy)
                        {
                            return;
                        }
                        if (tickerChangeEvent != null)
                            tickerChangeEvent(this, tck);
                        oldTck = tck;
                    }
                    catch (AggregateException ex)
                    {
                        string s = ex.ToString();
                        foreach (var item in ex.InnerExceptions)
                        {
                            s += "\r\n" + item.ToString();
                        }
                        Log.Default().Error($"定时获取数据异常-{GetExchangeSign()}-内部：" + s);
                    }
                    catch (Exception ex)
                    {
                        Log.Default().Error($"定时获取数据异常-{GetExchangeSign()}：" + ex.ToString());
                    }
                    finally
                    {
                        nowNum--;
                    }
                }
            };
        }
        Timer timer;
    }
}
